package com.example.weight.wormHandle.garbageDisposal.researchDevelopment;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.arrayAdapter.Item;
import com.example.weight.arrayAdapter.ItemAdapter;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class IncomingSceneMix extends AppCompatActivity implements View.OnClickListener{
    private String name, factory;
    private TitleBar titleBar;
    private String device_name;

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    private List<BatchGroupNumber> batchGroupNumberList;
    private Spinner batchGroupNumber;
    private int belongTo_id = -1;
    private TextView mix_data;
    private TextView mix_start;
    private TextView mix_end;
    private Button btn_mix_start;
    private Button btn_mix_end;
    private List<String> deviceNameList;
    private Spinner deviceName_2;
    private EditText remark;
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.incoming_scene_mix);

        titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                IncomingSceneMix.this.finish();
            }

            @Override
            public void onTitleClick(View v) {
            }

            @Override
            public void onRightClick(View v) {
            }
        });
        batchGroupNumberList = new ArrayList<>();
        batchGroupNumber = findViewById(R.id.batch_group_number_list);
        mix_data = findViewById(R.id.incoming_scene_mixDate);
        mix_data.setText(simpleDateFormat.format(incomingDate));

        mix_start = findViewById(R.id.mix_start);
        mix_start.setOnClickListener(this);
        mix_end = findViewById(R.id.mix_end);
        mix_end.setOnClickListener(this);
        btn_mix_start = findViewById(R.id.btn_mix_start);
        btn_mix_end = findViewById(R.id.btn_mix_end);
        btn_mix_start.setOnClickListener(this);
        btn_mix_end.setOnClickListener(this);
        deviceNameList = new ArrayList<>();
        deviceName_2 = findViewById(R.id.incoming_scene_deviceName_2);
        remark = findViewById(R.id.incoming_scene_remark);

        //如果甲方bb就先把这个注释掉
        deviceName_2.setEnabled(false);

        //获取待分离设备列表
        RequestQueue queue = Volley.newRequestQueue(this);
        String url2 = Config.url + "/research/mix/getList" + "?factory=" + factory;
        StringRequest stringRequest2 = new StringRequest(Request.Method.GET, url2,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONArray data = jsonObject.getJSONArray("data");
                                Log.d("TAG", data.toString());
                                if( data.length()>0){
                                    for (int i=0; i < data.length(); i++){
                                        JSONObject record = data.getJSONObject(i);
                                        Log.d("sr",record.toString());
                                        batchGroupNumberList.add(new BatchGroupNumber(record.getInt("id"),record.getString("batch"),record.getString("zubie"),record.getString("boxNumber"),"",""));
//                                        batchGroupNumberList.add(new BatchGroupNumber(record.getInt("id"),record.getString("batch"),record.getString("zubie"),record.getString("boxNumber"),record.getString("deviceName1")));
                                        deviceNameList.add(new String(record.getString("deviceName1")));
                                    }
                                    ArrayAdapter<BatchGroupNumber> adapter = new ArrayAdapter<BatchGroupNumber>(IncomingSceneMix.this, android.R.layout.simple_spinner_item,batchGroupNumberList);
                                    batchGroupNumber.setAdapter(adapter);
                                    batchGroupNumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            belongTo_id = batchGroupNumberList.get(position).id;
                                            deviceName_2.setSelection(position);
                                        }
                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {
                                            belongTo_id = -1;
                                        }
                                    });

                                    batchGroupNumber.setSelection(0,true);

                                    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(IncomingSceneMix.this, android.R.layout.simple_spinner_item,deviceNameList);
                                    deviceName_2.setAdapter(adapter1);
                                    deviceName_2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                                        @Override
                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                            device_name = deviceNameList.get(position);
                                        }
                                        @Override
                                        public void onNothingSelected(AdapterView<?> parent) {
                                            device_name = "";
                                        }
                                    });
                                    deviceName_2.setSelection(0,true);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(IncomingSceneMix.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest2.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest2);

//        // 获取设备名称
//        String url = Config.url + "/research/crush/getlast" + "?factory=" + factory;
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            Log.d("jy",response.toString());
//                            JSONObject data;
//                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
//                                data = jsonObject.getJSONObject("data");
//                                if (!data.isNull("id")) {
//                                    deviceNameList.add(data.getString("deviceName1"));
//                                    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(IncomingSceneMix.this, android.R.layout.simple_spinner_item,deviceNameList);
//                                    deviceName_2.setAdapter(adapter1);
//                                    deviceName_2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                                        @Override
//                                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                                            device_name = deviceNameList.get(position);
//                                        }
//                                        @Override
//                                        public void onNothingSelected(AdapterView<?> parent) {
//                                            device_name = "";
//                                        }
//                                    });
//
//                                    deviceName_2.setSelection(0,true);
////                                    deviceName_2.setText();
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(IncomingSceneMix.this,
//                        "获取设备名称失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest);

    }
    /**
     * 提交内容并设置输入缓存
     * @param view
     */
    public void save(View view) {
        if (belongTo_id == -1) {
            Toast.makeText(this, "请选择批次、组别、中虫盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mix_start.getText().toString().equals("")) {
            Toast.makeText(this, "请填写混料开始时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mix_end.getText().toString().equals("")) {
            Toast.makeText(this, "请填写混料结束时间", Toast.LENGTH_SHORT).show();
            return;
        }if (device_name.equals("")){
            Toast.makeText(this, "请填写设备名称", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    //提交请求
                    incomingDate = new Date(System.currentTimeMillis());
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/research/mix/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")) {
                                            Toast.makeText(IncomingSceneMix.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                            Intent intent = getIntent();
                                            finish();
                                            startActivity(intent);
                                        }
                                        else
                                            Toast.makeText(IncomingSceneMix.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
//                                    Log.d("jy", response);
//                                    if (response.toString().equals("true"))
//                                        Toast.makeText(IncomingSceneMix.this,
//                                                "保存成功", Toast.LENGTH_SHORT).show();
//                                    else
//                                        Toast.makeText(IncomingSceneMix.this,
//                                                "保存失败", Toast.LENGTH_SHORT).show();
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(IncomingSceneMix.this, "保存失败", Toast.LENGTH_SHORT).show();
                            Log.d("jy", error.toString());
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            //================================待修改===========================================
                            map.put("belongToId",belongTo_id+"");
                            map.put("deviceName2",  device_name);
                            map.put("mixStarttime", mix_start.getText().toString());
                            map.put("mixEndtime", mix_end.getText().toString());
                            map.put("remark", remark.getText().toString());
                            map.put("recorder",name);
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    Log.d("belongTo_id", "save: "+belongTo_id+"");
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }


    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(String.format("%02d", hourOfDay) + ":" + String.format("%02d", minute));
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.HOUR_OF_DAY)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }
    @Override
    public void onClick(View view) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        switch (view.getId()) {
            case R.id.btn_mix_start:
                Date date_1_start = new Date(System.currentTimeMillis());
                String s_1_start = simpleDateFormat.format(date_1_start);
                mix_start.setText(s_1_start);
                btn_mix_start.setEnabled(false);
                break;
            case R.id.btn_mix_end:
                Date date_1_end = new Date(System.currentTimeMillis());
                String s_1_end = simpleDateFormat.format(date_1_end);
                mix_end.setText(s_1_end);
                btn_mix_end.setEnabled(false);
                break;
            case R.id.mix_start:
                showTimePickerDialog(this,  2, mix_start, calendar);;
                break;
            case R.id.mix_end:
                showTimePickerDialog(this,  2, mix_end, calendar);;
                break;
            default:
                break;
        }
    }
}